<template>
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="3"
      labelWidth="160"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls" slot-scope="props">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="showAddNew = true">新增</el-button>
      </template>
    </FilterTable>
    <Drawer
      :visible.sync="visible"
      title="分配权限"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <AssignPermissions ref="AssignPermissions" @close="closeHandler" :showFun="showFun" :isShow="isShow" :rowData="rowData" :roleCode="roleCode" :isValid="isValid" :roleId='roleId' :roleName="roleName"/>
    </Drawer>
    <BaseDialog
      :visible.sync="showAddNew"
      title="角色信息新增"
      width="30%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto'}">
      <AddForm @close="closeDialog" @showDrawer="showDrawer"/>
    </BaseDialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import {getRoleList,addRole,deleteRole,findTcCodeByType} from '@/api/common/auth/roleManage';
import * as types from '@/api/common/auth/roleManage/types';
import AddForm from './addForm';
import AssignPermissions from './assignPermissions';

export default {
  name: 'Rolemanage',
  mixins: [dictionary],
  components: {
    AddForm,
    AssignPermissions
  },
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createTopFilterList(),
      visible: false,
      fetchApi: getRoleList,
      fetchParams: { xhrAbort: false,type:1, },
      columns: this.createTableColumns(),
      showAddNew: false,
      roleId: '',
      roleCode:'',
      roleName:'',
      rowData:'',
      isValid:"",
      roleData:[],
      isShow:"",
      showFun:"",
    };
  },
  methods: {
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 140,
          fixed: 'left',
          render: props => {
            /* 
             <el-divider direction="vertical" />
                <el-button size="mini" type="text" disabled={props.row.dataSource == 10451002?true:false} onClick={ ()=>this.showHandle(props.row.roleId,props.row.roleName,props.row) }>
                  查看
                </el-button>
            */
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.isPermission(props.row)} onClick={ ()=>this.permissionFun(props.row.roleId,props.row.roleName,props.row) }>
                  编辑
                </el-button>
               
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" disabled={this.isPermission(props.row)} onClick={ ()=>this.showDeleteFun(props.row.roleId) }>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '经销商角色代码',
          dataIndex: 'roleCode',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input',
          // align:"center"
        },
        {
          title: '经销商角色名称',
          dataIndex: 'roleName',
          sorter: true,
          filter: true,
          filterType: 'input',
          // align:"center"
          
        },
        {
          title: '经销商角色属性',
          dataIndex: 'codeCnDesc',
          sorter: true,
          filter: true,
          filterType: 'input',
          // sorter: true,
          // filter: true,
          // filterType: 'checkbox',
          // filterItems: [],
          // render: props => {
          //   return <span>{this.isOk(props.row.positionCode)}</span>;
          // }
        },
        {
          title: '是否关键岗位',
          dataIndex: 'isValid',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          hidden:false,
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isValid, '1004')}</span>;
          }
        },
        /* {
          title: '数据来源',
          dataIndex: 'dataSource',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          hidden:false,
          filterItems: this.createDictList('1045'),
          render: props => {
            return <span>{this.createDictText(props.row.dataSource, '1045')}</span>;
          }
        } */
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '经销商角色代码',
          fieldName: 'roleCode',
          placeholder: '角色代码...',
          style: { width: '200px' },
        },
        {
          type: 'INPUT',
          label: '经销商角色名称',
          fieldName: 'roleName',
          placeholder: '角色名称...',
          style: { width: '200px' },
        },
         {
          type: 'SELECT',
          label: '经销商角色属性',
          fieldName: 'positionCode',
          placeholder: '角色属性...',
          style: { width: '200px' },
          itemList: [],
        }
      ];
    },
    init(){
      
      let positionCodeData = this.createDictList('1006').concat(this.createDictList('1007'))
      // console.log(positionCodeData,"123")
      this.topFilterList.find(item=>item.fieldName == 'positionCode').itemList=positionCodeData
    },
    getCookie(){
        let allCookie=document.cookie.split(';')
        allCookie.forEach(x=>{
          if(x.indexOf('dataType') > -1 ){
            this.dataType=x.split('=')[1]
            }
        })
        //判断是否为车厂10461003
        console.log(this.dataType,"dataType")
        if(this.dataType == 10461003){
          console.log(this.dataType,"车厂",this.columns)
          // this.columns.find(item => item.fieldName === 'dataSource').hidden=true
          this.columns[5].hidden=true
          this.isShow=true
        }else{
          this.isShow=false
        }
      },
      // 编辑
    isPermission(row) {
      if(row.compile == 10041002){
        return true;
      } else {
        return false;
      }

      if (row.roleCode==='SYSADMIN') {
        return true;
      } else {
        return false;
      }
    },
    
    // 删除
    showDeleteFun(roleId) {
      this.$confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await deleteRole(roleId)
          if(res.errMsg) {
            this.$notify.error({title: '提示信息',message:res.errMsg||'删除失败!'});
          }else {
            this.$notify.success({title: '提示信息',message:'删除成功!'});
            // 重新加载
            this.fetchParams = { ...this.fetchParams };
          }
        }).catch(() => {
          // this.$notify.info({title: '提示信息',message:'已取消删除'});
        });
    },
    changeHandle(val) {
      val.type=1
      this.fetchParams = Object.assign({}, val, { xhrAbort: false });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    closeDialog(val,type) {
      this.showAddNew = val
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    async getRoleData(){
        await findTcCodeByType(1006).then(res => {
          _.cloneDeep(res.data).forEach(x=>{
            this.columns[4].filterItems.push({ text: x.codeCnDesc, value: x.codeId }) 
          })
        })
        await findTcCodeByType(1007).then(res => {
           _.cloneDeep(res.data).forEach(x=>{
            this.columns[4].filterItems.push({ text: x.codeCnDesc, value: x.codeId }) 
          })
        })
        this.columns[4].filterItems=this.roleData
        console.log(this.columns,"this.roleData")
       
    },
    permissionFun(roleId,roleName,row) {
      this.visible = true;
      this.roleId = String(roleId);
      this.roleName=roleName
      this.roleCode=row.roleCode
      this.rowData=row
      this.isValid=row.isValid
      this.showFun="edit"
    },
    // 查看
    showHandle(roleId,roleName,row){
      this.showFun="show"
      this.visible = true;
      this.roleId = String(roleId);
      this.roleName=roleName
      this.roleCode=row.roleCode
      this.rowData=row
    },
    //配置权限功能
    showDrawer(type,deployData){
      this.visible = type;
      this.roleId = deployData.roleId
      this.roleCode=deployData.roleCode
      this.roleName=deployData.roleName
      this.isValid=deployData.isValid
    },
    closeHandler(val,type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.init()
    this.getCookie()
    this.getRoleData()
  }
};
</script>

<style lang="less" scoped>
</style>
